package com.hellobike.haxing.modules.product.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hellobike.haxing.common.annotation.AutoLog;
import com.hellobike.haxing.common.system.base.controller.BaseController;
import com.hellobike.haxing.common.system.query.QueryGenerator;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.product.entity.FrontCategory;
import com.hellobike.haxing.modules.product.entity.Product;
import com.hellobike.haxing.modules.product.service.IFrontCategoryService;
import com.hellobike.haxing.modules.product.service.IProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 售卖商品
 * @Author: haxing-boot
 * @Date: 2020-01-17
 * @Version: V1.0
 */
@RestController
@RequestMapping("/product/product")
@Slf4j
public class ProductController extends BaseController<Product, IProductService> {
    @Autowired
    private IProductService productService;
    @Autowired
    private IFrontCategoryService frontCategoryService;

    /**
     * 分页列表查询
     *
     * @param product
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "售卖商品-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(Product product,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   @RequestParam(name = "frontCategoryId1", required = false) Long frontCategoryId1,
                                   HttpServletRequest req) {
        QueryWrapper<Product> queryWrapper = QueryGenerator.initQueryWrapper(product, req.getParameterMap());

        if (frontCategoryId1 != null) {//限定只展示该前台目录下包含的商品
            Set<Long> includeProductIds = new HashSet<>();
            Set<Long> includeThirdCategoryIds = new HashSet<>();
            includeProductIds.add(-1L);//防止in空集合报错
            includeThirdCategoryIds.add(-1L);//同上
            QueryWrapper<FrontCategory> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.lambda().eq(FrontCategory::getParentId, frontCategoryId1);
            List<FrontCategory> frontCategoryList = frontCategoryService.list(queryWrapper1);
            for (FrontCategory frontCategory : frontCategoryList) {
                JSONObject aggregation = frontCategory.getAggregation();
                if (aggregation != null) {
                    Integer type = aggregation.getInteger("type");
                    JSONArray ids = aggregation.getJSONArray("ids");
                    List<Long> idList = ids.toJavaList(Long.class);
                    if (type == 1) {//聚合商品
                        includeProductIds.addAll(idList);
                    } else if (type == 2){//聚合分类
                        includeThirdCategoryIds.addAll(idList);
                    }
                }
            }
            queryWrapper.and(wrapper -> wrapper.in("id", includeProductIds).or().in("category_id3", includeThirdCategoryIds));
        }
        Page<Product> page = new Page<Product>(pageNo, pageSize);
        IPage<Product> pageList = productService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param product
     * @return
     */
    @AutoLog(value = "售卖商品-添加", operateType = 2)
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody Product product) {
        productService.saveProduct(product);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param product
     * @return
     */
    @AutoLog(value = "售卖商品-编辑", operateType = 3)
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody Product product) {
        productService.updateProduct(product);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "售卖商品-删除", operateType = 4)
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) Long id) {
        productService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "售卖商品-批量删除", operateType = 4)
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.productService.removeByIds(Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) Long id) {
        Product product = productService.getProductDetail(id);
        if (product == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(product);
    }

    /**
     * 根据id列表批量查询
     *
     * @param ids
     * @return
     */
    @GetMapping(value = "/queryByIds")
    public Result<?> queryByIds(@RequestParam(name = "ids", required = true) String ids) {
        List<Product> productList = productService.getByIds(Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()));
        return Result.ok(productList);
    }

    /**
     * 上下架
     * @param id
     * @param onlineStatus
     * @return
     */
    @GetMapping(value = "/changeOnlineStatus")
    public Result<?> changeOnlineStatus(@RequestParam(name = "id", required = false) Long id, @RequestParam(name = "onlineStatus", required = false) Integer onlineStatus) {
        Product product = new Product();
        product.setId(id);
        product.setOnlineStatus(onlineStatus);
        productService.updateById(product);
        return Result.ok("操作成功!");
    }

    /**
     * 批量上下架
     * @param ids
     * @param onlineStatus
     * @return
     */
    @GetMapping(value = "/batchChangeOnlineStatus")
    public Result<?> batchChangeOnlineStatus(@RequestParam(name = "ids", required = false) String ids, @RequestParam(name = "onlineStatus", required = false) Integer onlineStatus) {
        List<Long> productIdList = Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        Product product = new Product();
        product.setOnlineStatus(onlineStatus);
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(Product::getId, productIdList);
        productService.update(product, queryWrapper);
        return Result.ok("操作成功!");
    }

    /**
     * 导出excel
     *
     * @param request
     * @param product
     */
    @AutoLog(value = "售卖商品-导出excel", operateType = 6)
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Product product) {
        return super.exportXls(request, product, Product.class, "售卖商品");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @AutoLog(value = "售卖商品-导入excel", operateType = 5)
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Product.class);
    }

}
